﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;

namespace LinkedInWinRT.Helpers
{
    public class OAuthUtil
    {
        public string GetNonce()
        {
            var rand = new Random();
            int nonce = rand.Next(1000000000);
            return nonce.ToString();
        }

        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public async Task<string> PostData(string url, string postData)
        {
            try
            {
                var httpClient = new HttpClient
                    {
                        MaxResponseContentBufferSize = int.MaxValue
                    };
                httpClient.DefaultRequestHeaders.ExpectContinue = false;
                var requestMsg = new HttpRequestMessage
                    {
                        Content = new StringContent(postData),
                        Method = new HttpMethod("POST"),
                        RequestUri = new Uri(url, UriKind.Absolute)
                    };
                requestMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                var response = await httpClient.SendAsync(requestMsg);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public string GetSignature(string sigBaseString, string consumerSecretKey, string requestTokenSecretKey = null)
        {
            IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(consumerSecretKey + "&" + requestTokenSecretKey,
                                                                            BinaryStringEncoding.Utf8);
            MacAlgorithmProvider algorithm = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            CryptographicKey key = algorithm.CreateKey(keyMaterial);
            IBuffer dataToBeSigned = CryptographicBuffer.ConvertStringToBinary(sigBaseString, BinaryStringEncoding.Utf8);
            IBuffer signatureBuffer = CryptographicEngine.Sign(key, dataToBeSigned);
            string signature = CryptographicBuffer.EncodeToBase64String(signatureBuffer);
            return signature;
        }
    }
}
